#define  _CRT_SECURE_NO_WARNINGS 1

#include "List.h"


LTNode* BuyLTNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	node->value = x;
	node->prev = NULL;
	node->next = NULL;
	return node;
}
LTNode* LTInit()
{
	LTNode* phead = BuyLTNode(0);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}
void LTDestory(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* tmp = cur;
		cur = cur->next;
		free(tmp);
	}

	free(phead);	
}
void LTPrint(LTNode* phead)
{
	assert(phead);

	printf("phead<=>");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->value);
		cur = cur->next;
	}
	printf("NULL\n");
}
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = BuyLTNode(x);
	LTNode* tail = phead->prev;

	newnode->next = phead;
	phead->prev = newnode;

	newnode->prev = tail;
	tail->next = newnode;

}
void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	free(tail);

	tailprev->next = phead;
	phead->prev = tailprev;


}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = BuyLTNode(x);
	LTNode* first = phead->next;

	newnode->prev = phead;
	phead->next = newnode;

	newnode->next = first;
	first->prev = newnode;

}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* first = phead->next;
	LTNode* second = first->next;

	free(first);

	phead->next = second;
	second->prev = phead;


}

int LTSize(LTNode* phead)
{
	assert(phead);

	int size = 0;
	
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->value == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}


void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	
	LTNode* prev = pos->prev;
	LTNode* newnode = BuyLTNode(x);

	prev->next = newnode;
	newnode->prev = prev;
	
	pos->prev = newnode;
	newnode->next = pos;
}
void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* posprev = pos->prev;
	LTNode* posnext = pos->next;

	free(pos);

	posprev->next = posnext;
	posnext->prev = posprev;

}
void LTModify(LTNode* pos, LTDataType x)
{
	assert(pos);

	pos->value = x;
}